package com.ggy.babybed.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ggy.babybed.R;
import com.ggy.babybed.activity.MyApplication;
import com.ggy.babybed.util.Utility;
import com.gitonway.lee.niftymodaldialogeffects.lib.Effectstype;
import com.gitonway.lee.niftymodaldialogeffects.lib.NiftyDialogBuilder;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

public class BabyInfoFragment extends Fragment {
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private static final String TAG = "BabyInfoFragment";
    private OnFragmentInteractionListener mListener;
    private RelativeLayout rlName;
    private RelativeLayout rlSex;
    private RelativeLayout rlAge;
    private RelativeLayout rlBirth;
    private RelativeLayout rlWeight;
    private TextView tName;
    private TextView tSex;
    private TextView tAge;
    private TextView tBirth;
    private TextView tWeight;
    private EditText text;
    private View inputView;
    private ImageView circleImage;
    private NiftyDialogBuilder dialog;

    public BabyInfoFragment() {
    }

    public static BabyInfoFragment newInstance(String param1, String param2) {
        BabyInfoFragment fragment = new BabyInfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            getArguments().getString(ARG_PARAM1);
            getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_baby_info, container, false);
        inputView = inflater.inflate(R.layout.input_textview, container, false);
        rlName = (RelativeLayout) view.findViewById(R.id.babyinfo_name);
        rlSex = (RelativeLayout)view.findViewById(R.id.babyinfo_sex);
        rlAge = (RelativeLayout)view.findViewById(R.id.babyinfo_age);
        rlBirth = (RelativeLayout)view.findViewById(R.id.babyinfo_birth);
        rlWeight = (RelativeLayout)view.findViewById(R.id.babyinfo_weight);
        tName = (TextView)view.findViewById(R.id.bi_name);
        tSex = (TextView)view.findViewById(R.id.bi_sex);
        tAge = (TextView)view.findViewById(R.id.bi_age);
        tBirth = (TextView)view.findViewById(R.id.bi_birth);
        tWeight = (TextView)view.findViewById(R.id.bi_weight);
        text = (EditText) inputView.findViewById(R.id.editText);
        circleImage = (ImageView) view.findViewById(R.id.babyinfo_icon);
        circleImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage();
            }
        });
        initInfo();
        handlClick();
        return view;
    }

    public void selectImage() {
        Intent i;
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            i = new Intent(Intent.ACTION_GET_CONTENT);
        } else {
            i = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        }
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(i, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1) {
            Uri uri = data.getData();
            Bitmap bitmap = null;
            if(uri != null){
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                }
            }
            if (bitmap == null) {
                Utility.showToast(getContext(), R.string.error_info);
            } else {
                circleImage.setImageBitmap(bitmap);
                String filePath = Utility.saveBitmap(bitmap, MyApplication.getHeadpicSavePath(), "babyheader");
                MyApplication.setValue(getString(R.string.bi_head_icon), filePath);
                Log.i(TAG, "[set image success]");
            }
        }
    }

    private void initInfo(){
        tName.setText(MyApplication.getValue(getString(R.string.bi_name)));
        tSex.setText(MyApplication.getValue(getString(R.string.bi_sex)));
        tAge.setText(MyApplication.getValue(getString(R.string.bi_age)));
        tBirth.setText(MyApplication.getValue(getString(R.string.bi_birth)));
        tWeight.setText(MyApplication.getValue(getString(R.string.bi_weight)));
        String path = MyApplication.getValue(getString(R.string.bi_head_icon));
        if(StringUtils.isNotBlank(path)){
            circleImage.setImageBitmap(BitmapFactory.decodeFile(path));
        }else{
            circleImage.setImageDrawable(getResources().getDrawable(R.drawable.head));
        }
    }

    private void initDialog(){
        if(null == dialog){
            dialog = NiftyDialogBuilder.getInstance(getContext());
        }
        dialog.withTitle(null).withMessage(null)
                .withDividerColor("#11000000")
                .withDialogColor("#FFDFADFE")
                .isCancelableOnTouchOutside(true)
                .withButton1Text("取消")
                .withButton2Text("确定")
                .withEffect(Effectstype.Fadein)
                .setCustomView(inputView, getContext())
                .setButton1Click(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
    }

    private void handlClick(){
        rlName.setOnClickListener(new ClickListener(tName, R.string.bi_name));
        rlSex.setOnClickListener(new ClickListener(tSex, R.string.bi_sex));
        rlAge.setOnClickListener(new ClickListener(tAge, R.string.bi_age));
        rlBirth.setOnClickListener(new ClickListener(tBirth, R.string.bi_birth));
        rlWeight.setOnClickListener(new ClickListener(tWeight, R.string.bi_weight));
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    private class ClickListener implements View.OnClickListener {
        private TextView textView;
        private int id;

        public ClickListener(TextView textView, int id) {
            this.textView = textView;
            this.id = id;
        }

        @Override
        public void onClick(View v) {
            text.setText(textView.getText() != null ? textView.getText() : "");
            initDialog();
            dialog.setButton2Click(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    textView.setText(text.getText() == null ? "" : text.getText());
                    MyApplication.setValue(getString(id), textView.getText().toString());
                    dialog.dismiss();
                }
            }).show();
        }
    }
}
